#!/usr/bin/php -q
<?php
	/**
	 * process_mail.php
	 * @author David Ivins
	 */

	# override the include path
	set_include_path(get_include_path() . PATH_SEPARATOR 
		. '/var/www/mobloggin/include' . PATH_SEPARATOR
		. '/var/www/mobloggin/include/lib' . PATH_SEPARATOR
		. '/usr/share/php/Zend');

	# obtain a mail processor and copy configuration
	require_once('MailProcessor.php');
	require_once('MailProcessorException.php');

	# create a new instance of the mail processor
	$mail_proc = new MailProcessor();
	$config = $mail_proc->getConfiguration();
	$mail_proc->log($_SERVER['SCRIPT_NAME'] . '::Script Invoked', 'debug');

	# configure script error reporting and logging
	ini_set('error_log', $config->path->logs->mail->file); 
	ini_set('error_reporting', E_ALL);
	ini_set('display_errors',FALSE);
	ini_set('log_errors',TRUE);
	error_reporting(E_ALL);

	# get email message as string from stdin
	$fd = fopen("php://stdin", "r");
	while (!feof($fd)) 
			$email = (isset($email)) ? $email . fread($fd, 1024) : fread($fd, 1024);
	fclose($fd);

	try 
	{
		# process the message
		$msg = new Zend_Mail_MessageFromString($email);
		$mail_proc->processMessage($msg);
		$mail_proc->log($_SERVER['SCRIPT_NAME'] . '::Mail Processing Script '
			. 'Completed Without Any Errors.', 'debug');
	}
	catch (MailProcessorException $e)
	{
		switch ($e->getCode())
		{
			case 4: // unable to store information in db.	not used yet...
				$mail_proc->log($_SERVER['SCRIPT_NAME'] . '::You have somehow hit the'
					. ' unused DB exception.', 'error');
				$mail_proc->log(print_r($msg, true), 'error'); 
				break;
			case 0:  // no user associated with from address
			case 1:  // message contains no attachments (not multipart)
			case 2:  // no attachments were recognized
			case 3:  // unable to store media to S3 storage
			default: // unknown exception code
				$mail_proc->log($e->getMessage(), 'error');
				$mail_proc->log(print_r($msg, true), 'error'); 
		}

		# script failed. send failure emails and mark failure in log
		$mail_proc->sendFailureEmails($msg);
		$mail_proc->log($_SERVER['SCRIPT_NAME'] . '::Mail Processing Script '
			. 'Failed.', 'error');
	}
	catch (Amazon_SimpleDB_Exception $e)
	{
		$mail_proc->log($e->getMessage(), 'error');
		$mail_proc->log(print_r($msg, true), 'error'); 
	}

	return true;
